<script lang="ts" setup>
import { h, ref, onMounted, computed } from 'vue';
import {
  NCard,
  NSpace,
  NDataTable,
  NButton,
  NPopconfirm,
  NDatePicker,
  NInput,
  useMessage,
  type DataTableColumns
} from 'naive-ui';
import { $t } from '@/locales';
import { getTranslationRecordList, deleteTranslationRecord } from '@/service/api/translation-record';
import { formatDateTime } from '@/utils';

// 表格加载状态
const loading = ref(false);

// 表格数据
const data = ref<Api.TranslationRecord.RecordInfo[]>([]);

// 分页信息
const pagination = ref({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
});

// 搜索条件
const searchParams = ref({
  mediaName: '',
  name: '',
  translatedLanguage: '',
  timeRange: null as [number, number] | null,
  sortField: 'createTime',
  sortOrder: 'desc'
});

// 消息提示
const message = useMessage();

// 表格列定义
const columns = computed<DataTableColumns<Api.TranslationRecord.RecordInfo>>(() => [
  {
    title: $t('common.index'),
    key: 'index',
    width: 80,
    render: (row, index) => index + 1 + (pagination.value.page - 1) * pagination.value.pageSize
  },
  {
    title: $t('page.recordfile.table.mediaName'),
    key: 'mediaName',
    width: 200
  },
  {
    title: $t('page.recordfile.table.name'),
    key: 'name'
  },
  {
    title: $t('page.recordfile.table.translatedLanguage'),
    key: 'translatedLanguage',
    width: 120
  },
  {
    title: $t('page.recordfile.table.mediaPath'),
    key: 'mediaPath',
    width: 200
  },
  {
    title: $t('page.recordfile.table.translatedPath'),
    key: 'translatedPath',
    width: 200
  },
  {
    title: $t('page.recordfile.table.createTime'),
    key: 'createTime',
    width: 180,
    render: (row) => formatDateTime(row.createTime)
  },
  {
    title: $t('common.action'),
    key: 'actions',
    width: 200,
    fixed: 'right',
    render: (row) => {
      return h(
        NSpace,
        { align: 'center', justify: 'center' },
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleOpenFolder(row.translatedPath)
              },
              { default: () => $t('common.openFolder') }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete([row.id])
              },
              {
                default: () => $t('common.confirmDelete'),
                trigger: () =>
                  h(
                    NButton,
                    {
                      size: 'small',
                      type: 'error'
                    },
                    { default: () => $t('common.delete') }
                  )
              }
            )
          ]
        }
      );
    }
  }
]);

// 获取列表数据
async function fetchData() {
  try {
    loading.value = true;
    const { timeRange, ...params } = searchParams.value;
    const res = await getTranslationRecordList({
      ...params,
      startTime: timeRange?.[0] ? new Date(timeRange[0]).toISOString() : undefined,
      endTime: timeRange?.[1] ? new Date(timeRange[1]).toISOString() : undefined,
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    });
    if (res.data) {
      data.value = res.data.result;
      pagination.value.itemCount = res.data.total;
    }
  } catch (error) {
    message.error($t('page.recordfile.message.loadFailed'));
  } finally {
    loading.value = false;
  }
}

// 处理页码变化
function handlePageChange(page: number) {
  pagination.value.page = page;
  fetchData();
}

// 处理每页条数变化
function handlePageSizeChange(pageSize: number) {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchData();
}

// 处理搜索
function handleSearch() {
  pagination.value.page = 1;
  fetchData();
}

// 处理重置
function handleReset() {
  searchParams.value = {
    mediaName: '',
    name: '',
    translatedLanguage: '',
    timeRange: null,
    sortField: 'createTime',
    sortOrder: 'desc'
  };
  pagination.value.page = 1;
  fetchData();
}

// 处理删除
async function handleDelete(ids: string[]) {
  try {
    await deleteTranslationRecord({ ids, deleteSourceFile: true });
    message.success($t('page.recordfile.message.deleteSuccess'));
    if (data.value.length === 1 && pagination.value.page > 1) {
      pagination.value.page--;
    }
    fetchData();
  } catch (error) {
    message.error($t('page.recordfile.message.deleteFailed'));
  }
}

// 处理打开文件夹
function handleOpenFolder(path: string) {
  if (!path) {
    message.warning($t('common.noData'));
    return;
  }
  // @ts-ignore
  window.electron?.openFolder(path);
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="translation-record">
    <NCard>
      <NSpace vertical :size="16">
        <!-- 搜索区域 -->
        <div class="search-area">
          <NSpace :size="16">
            <NInput
              v-model:value="searchParams.mediaName"
              :placeholder="$t('page.recordfile.search.mediaName')"
              @keydown.enter="handleSearch"
            />
            <NInput
              v-model:value="searchParams.name"
              :placeholder="$t('page.recordfile.search.name')"
              @keydown.enter="handleSearch"
            />
            <NDatePicker
              v-model:value="searchParams.timeRange"
              type="datetimerange"
              clearable
              :placeholder="$t('page.recordfile.search.date')"
            />
            <NSpace>
              <NButton type="primary" @click="handleSearch">
                {{ $t('common.search') }}
              </NButton>
              <NButton @click="handleReset">
                {{ $t('common.reset') }}
              </NButton>
            </NSpace>
          </NSpace>
        </div>

        <!-- 表格 -->
        <NDataTable
          :loading="loading"
          :columns="columns"
          :data="data"
          :pagination="pagination"
          :scroll-x="1200"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </NSpace>
    </NCard>
  </div>
</template>

<style scoped>
.translation-record {
  padding: 16px;
}

.search-area {
  padding: 16px;
  border-radius: 6px;
  border: 1px solid var(--n-border-color);
  background-color: var(--n-color-light);
}
</style>
